How do you make a precise countdown timer using clock_gettime? [migrated]

Posted by Joshun on Programmers See other posts from Programmers or by Joshun
Published on 2012-12-16T19:20:09Z Indexed on 2012/12/16 23:19 UTC
Read the original article Hit count: 150

Filed under:
|
|

Could somebody please explain how to make a countdown timer using clock_gettime, under Linux. I know you can use the clock() function to get cpu time, and multiply it by CLOCKS_PER_SEC to get actual time, but I'm told the clock() function is not well suited for this.

So far I have attempted this (a billion is to pause for one second)

#include <stdio.h>
#include <time.h>

#define BILLION 1000000000

int main()
{
 struct timespec rawtime;
 clock_gettime(CLOCK_MONOTONIC_RAW, &rawtime);
 unsigned long int current =  ( rawtime.tv_sec + rawtime.tv_nsec );
 unsigned long int end =  (( rawtime.tv_sec + rawtime.tv_nsec ) + BILLION );
 while ( current < end )
 {
  clock_gettime(CLOCK_MONOTONIC_RAW, &rawtime);
  current =  ( rawtime.tv_sec + rawtime.tv_nsec );
 }

 return 0;
}

I know this wouldn't be very useful on its own, but once I've found out how to time correctly I can use this in my projects. I know that sleep() can be used for this purpose, but I want to code the timer myself so that I can better integrate it in my projects - such as the possibility of it returning the time left, as opposed to pausing the whole program.

© Programmers or respective owner

Related posts about c

    Related posts about linux